#导入蓝图模块
from flask import Blueprint,request
from flask.json import jsonify

from dbb import db1
import json

from utils.myfile import myfile
# #实例化
bp_course = Blueprint("course",__name__)

# #接口

# @bp_course.route('/couponM',methods=['POST',"GET",'PUT','DELETE'])
# def couponM():
#     #添加
#     if request.method == "POST":
#         #获取用户输入
#         data = request.data
#         if data:
#             data = json.loads(data)
#         else:
#             data = request.form
#         #构造sql语句
#         sql = "insert into coupon values(0,'%s',%d,'%s','%s')"%(data['name'],int(data['total']),data['stime'],data['etime'])
#         #pymysql
#         db1.insert(sql)
#         #返回结果
#         return 'ok'
#     elif  request.method == "PUT":
#         #修改
#         #获取用户输入
#         data = request.data
#         if data:
#             data = json.loads(data)
#         else:
#             data = request.form
#         #构造sql语句 update 表名 set 字段名1=值，字段名2=值 where id=1
#         sql = "update coupon set name='%s',total=%d,starttime='%s',endtime='%s' where id=%d"%(data['name'],int(data['total']),data['stime'],data['etime'],int(data['id']))
#         db1.insert(sql)
#         return jsonify({"code":200})
#     elif request.method=="DELETE":
#         #获取 id
#         id=request.args.get('id')
#         sql="delete from coupon where id=%d"%(int(id))
#         db1.insert(sql)
#         return jsonify({"code":200})
#     else:
#         id=request.args.get('id')
#         sql="select * from coupon where id=%d"%(int(id))
#         res=db1.find(sql)
#         return jsonify({"code":200,'coupon':res})
    
def get_data():
    data=request.data
    if data:
        data=json.loads(data)
    else:
        data=request.form
    return data

import os    
#文件上传
@bp_course.route('/upload',methods=['POST'])
def upload():
    #获取文件
    file = request.files['file']
    #选择文件夹
    #创建文件夹
    myfile.file_mkdir(2)
    #保存文件
    file.save(os.path.join('./static/upload/2/',file.filename))
    #保存 /static/upload/1/
    return 'ok'
@bp_course.route('/citym')
def citym():
    sql="select id,name from city"
    res=db1.findall(sql)
    return jsonify({"code":200,'list':res})

#发红包200-0.01区间接口
@bp_course.route('/sendmoney')
def sendmoney():
    money = request.args.get('money')
    #对数据进行有效性验证
    if not money:
        return jsonify({"code":10010,"mes":'请输入金额'})
    else:
        try:
             #格式验证
             money = float(money)
        except:
            return jsonify({'code':10012,'mes':'格式有误'})
    if money<200 and money>0.01:
        return jsonify({"code":200})
    else:
        return jsonify({"code":10013})   

@bp_course.route('/sendMony',methods=['POST'])
def sendMony():
    data = get_data() 
    sql = "insert into test_record(name,url,method,params,result) values('%s','%s','%s','%s','%s')"%(data['name'],data['url'],data['method'],data['params'],data['result'])
    db1.insert(sql)
    return jsonify({"code":200})

import requests
import datetime
@bp_course.route('/test_sendMoney')
def test_sendMoney():
    #读取数据库
    sql = "select * from test_record where status=1"
    res = db1.findall(sql)
    list=[]
    for i in res:
        flag = "失败"
        params = json.loads(i['params'])
        if i['method'] == "get":
            mes = requests.get(i['url'],params=params)
        elif i['method'] == "post":
            mes = requests.post(i['url'],data=params)
        mm = json.loads(mes.text)
        if mm['code'] == int(i['result']):
            flag='成功'
        str={"name":i['name'],"请求地址":i['url'],"返回信息":mes.text,"测试结果":flag}
        list.append(str)
        filename = datetime.datetime.strftime(datetime.datetime.now(),'%Y%m%d')
        with open(os.path.join('./logs/'+filename+'.txt'),'w') as f:
            f.write(json.dumps(list,ensure_ascii=False))
   
    return jsonify({"code":200})
import re
# import get_data
import time
# @bp_course.route('/sendSms',method=['POST'])
# def sendSms():
#     #获取手机号
#     data=gat_data()
#     try:
#         mobile=data['mobile']
#     except:
#         return jsonify({"code":10011,'mes':'不能为空'})
#     #验证手机号是否合法
#     res=re.match('1[3-9]\d{9}$',data['mobile'])
#     if not res:
#         return jsonify({"code":10010,'mes':'手机号不合法'})
#     sql="select stime from trecord where mobile='%s' order by id desc limit 1"%(str(mobile))
#     #检查上次发送是否超过一分钟,1分钟内不能发
#     record=db1.find(sql)
#     if record:
#         seconds=int(time.time())-int(record['stime'])
#         if seconds<60:
#             return jsonify(({"code":10012}))
#     #生成验证码,发送
#     code=random.randint(100000,999999)
#     #当发送成功写入记录表
#     sql2="insert into trecord(mobile,code,stime) values('%s',%d,%d)"
#     #返回结果
#     return pass

@bp_course.route('/tlogin',methods=['POST'])
def tlogin():
    
    #获取手机号验证码
    data=get_data()
    #通过手机号去记录中表查询,查最近的一条
    sql="select code,stime from trecord where mobile='%s' order by id desc limit 0,1"%(data['mobile'])
    res=db1.find(sql)
    #验证码过期时间验证
    if int(time.time())-int(res['stime'])>60:
        return jsonify({"code":10020,"mes":'验证码已过期'})
    #验证是否相同
    if res['code']==int(data['code']):
    #用户表中查询手机号是否存在
        sql1="select id from tuser where mobile='%s'"%(data['mobile'])
        user=db1.find(sql1)
    #存在返回登录成功userid
        if user:
            return jsonify({"code":200,'userid':user['id'],'mes':'登录成功'})
    #不存在添加新用户返回userid
        sql2="insert into tuser(mobile) values(%s)"%(data['mobile'])
        db1.insert(sql2)
        sql3="select id from tuser where mobile='%s'"%(data['mobile'])
        user3=db1.find(sql3)
        return jsonify({"code":200,'userid':user3['id']})    
    else:
        return jsonify({"code":10021,'mes':'验证码输入错误'})

# @bp_course.route('/prom',methods=['POST'])
# def prom():
#    data = get_data()
#    sql = "insert into product(title,price,city_id,pic) values('%s',%.2f,%d,'%s')"%(data['title'],float(data['price']),int(data['city_id']),data['pic'])
#    db1.insert(sql)
#    return jsonify({"code":200})

    # else:
    #     #根据分类id查询分类下商品
    #     cityid = request.args.get('cityid')
    #     if  cityid == '0':
    #         sql = "select * from product"
    #     else:
    #         sql = "select * from product where city_id=%d"%(int(cityid))
    #     res = db1.findall(sql)
    #     return jsonify({"code":200,'list':res})
    
    #获取订单接口
# @bp_course.route('/orderM')
# def orderM():
#     sql = 'select * from orders'
#     res = db1.findall(sql)
#     return jsonify({"code":200,'list':res})
# #获取分类接口
# @bp_course.route('/orderM',methods=['GET','PUT'])
# def orderM():
#     if request.method == "PUT":
#         id = request.args.get('id')
#         sql = "select * from orders where id=%d"%(int(id))
#         res = db1.find(sql)
#         #判断状态原来为1改成2，原来为2改成1
#         status = 2
#         if int(res['status']) == 2:
#             status=1            
        
#         #执行更新操作
#         sql1 = "update orders set status=%d where id=%d"%(status,int(id))
#         db1.insert(sql1)
#         return jsonify({"code":200})

#     else:
#         #当前页
#         page = int(request.args.get('page'))
#         #每页显示多少条
#         page_size = int(request.args.get('page_size'))
#         start = (page-1)*page_size
#         sql = 'select * from orders limit %d,%d'%(start,page_size)
#         res = db1.findall(sql)
#         #总条数
#         sql1 = "select count(id) from orders"
#         res1 = db1.find(sql1)
#         return jsonify({"code":200,'list':res,'total':res1['count(id)']})

